package com.sushe.utils;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public  class JDBCUtils {
    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;

    static {
        try {
            Properties pro=new Properties();
            InputStream is=Thread.currentThread().getContextClassLoader().getSystemResourceAsStream("jdbc.properties");
            pro.load(is);
            driverClass=pro.getProperty("driverClass");
            url=pro.getProperty("url");
            user=pro.getProperty("user");
            password=pro.getProperty("password");
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getconnection() throws SQLException {//获取数据库连接对象 Connection
        return DriverManager.getConnection(url,user,password);
    }
    /**
     *重载方式实现close方法：
     *1.当执行SQL的增、删、改语句时，使用void close(Statement ,Connection)来关闭资源
     *2.当执行SQL的查询语句时，使用void close(ResultSet,Statement ,Connection)来关闭资源
     */
    public static void close(Statement statement,Connection connection){//释放资源
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(ResultSet resultSet,Statement statement,Connection connection){//释放资源
        close(statement,connection);
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

